using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.ServiceLocation;

using MvcCms.Service.Code;

using MvcCms.Data;
using MvcCms.Data.Pagination;
using MvcCmsWiki.Data;
using MvcCms.Service.Cache;
using MvcCms.Service.Logging;

namespace MvcCmsWiki.Service
{
    public class WikiService : IWikiService
    {
        #region Constructors

        private readonly ICacheService _cacheService;
        private readonly IWikiRepository _repository;

      

        public WikiService(IWikiRepository repository, ICacheService cacheService)
        {
            _repository = repository;
            _cacheService = cacheService;
        }

        #endregion

        #region Validation Methods



        #endregion

        #region Wiki Methods

        public DTOWikiContent Get(string slug)
        {
            var content = _repository.Get(slug, _cacheService.GetCurrentPortal().PortalID);
            if (content != null)
            {
                var wikiTitle = _repository.GetTitle(content.WikiTitle.TitleID);
                content.WikiTitle.MaxVersion = wikiTitle.WikiContents.Count;
                return new DTOWikiContent
                {
                    ContentID = content.ContentID,
                    WikiTitle = content.WikiTitle,
                    Source = content.Source,
                    Version = content.Version,
                    VersionDate = content.VersionDate,
                    IsCurrentVersion = content.IsCurrentVersion
                };
            }
            return null;
        }
        public WikiSetting GetSettings()
        {
            return _repository.GetSettings(_cacheService.GetCurrentPortal().PortalID);
        }
        public DTOWikiContent GetByVersion(string slug, int version)
        {
            var content = _repository.GetByVersion(slug, version, _cacheService.GetCurrentPortal().PortalID);

            if (content != null)
            {
                var wikiTitle = _repository.GetTitle(content.WikiTitle.TitleID);
                content.WikiTitle.MaxVersion = wikiTitle.WikiContents.Count;
                return new DTOWikiContent
                {
                    ContentID = content.ContentID,
                    WikiTitle = content.WikiTitle,
                    Source = content.Source,
                    Version = content.Version,
                    VersionDate = content.VersionDate,
                    IsCurrentVersion = content.IsCurrentVersion 
                };
            }
            return null;
        }
        public IEnumerable<DTOWikiContent> GetDTOHistory(string slug, int pageNumber, int resultsPerPage)
        {
            var historys = QueryExtensions.SortBy
                                            (
                                                _repository.GetHistory(slug, _cacheService.GetCurrentPortal().PortalID)
                                                .AsQueryable(), "Version DESC"
                                            )
                                            .AsPagination(pageNumber, resultsPerPage)
                                            .ToList();            
            
            if (historys.Count()>0)
            {
                IList<DTOWikiContent> historyToReturn = new List<DTOWikiContent>();
                foreach (var history in historys)
                {
                    var newhistory = new DTOWikiContent
                    {
                        ContentID = history.ContentID,
                        Source = "",
                        UserName =  history.User.UserName.ToProfileLink(),
                        Version = history.Version,
                        VersionDate = history.VersionDate,
                        IsCurrentVersion = history.IsCurrentVersion
                    };
                    historyToReturn.Add(newhistory);
                }
                return historyToReturn;
            }
            return null;
        }

        public IEnumerable<WikiContent> GetHistory(Guid userId)
        {
            return _repository.GetHistory(userId);
        }
        public WikiSetting SaveSettings(WikiSetting wikiSettingsToEdit)
        {
            // Database logic
            try
            {
                if (wikiSettingsToEdit.WikiSettingID == 0)
                {
                   
                    var portalRepository = ServiceLocator.Current.GetInstance<IPortalRepository>();

                    wikiSettingsToEdit.Portal = portalRepository.GetPortal(_cacheService.GetCurrentPortal().PortalID);
                    _repository.CreateWikiSettings(wikiSettingsToEdit);
                }
                else
                {
                    _repository.EditWikiSettings(wikiSettingsToEdit);
                }
                return wikiSettingsToEdit;
            }
            catch (Exception ex)
            {
                AppLogging.GetLogger().Error(GeneralMethods.GetStackNames(), ex);
                return null;
            }
        }
        public bool Save(string slug, string title, string source, User user, string restrictedToGroups)
        {
            // Database logic
            try
            {
               
                var portalRepository = ServiceLocator.Current.GetInstance<IPortalRepository>();

                var portal = portalRepository.GetPortal(_cacheService.GetCurrentPortal().PortalID);
                _repository.Save(slug, title, source, portal, user, restrictedToGroups);
            }
            catch (Exception ex)
            {
                AppLogging.GetLogger().Error(GeneralMethods.GetStackNames(), ex);
                return false;
            }
            return true;
        }

        #endregion


    }
}